# Copyright (c) 2022 Presto Labs Pte. Ltd.
# Author: taekwon

from absl import app, flags
from datetime import datetime

from coin.exchange.bithumb.kr_rest.native_private_client import BithumbNativePrivateClient


def init_flags():
  flags.DEFINE_string('key_file',
                      '/home/ec2-user/config/trade/chpark0/bithumb/trade_key.json',
                      'key file path')
  flags.DEFINE_string('currency', 'BTC', 'currency')
  flags.DEFINE_string('query_type', '0', 'query type(0:summary, 1:by fill)')
  flags.DEFINE_string('init_offset', '0', 'by fill initial offse')
  flags.DEFINE_string('fetch', '1000', 'by fill fetch count')
  flags.DEFINE_string('filter_date', '', 'filter date range')


class MySpotClient(BithumbNativePrivateClient):
  def __init__(self, key_file):
    super().__init__(api_host="club.bithumb.com", key_file=key_file)

  def query_ticker(
      self,
      order_currency: str,
  ):
    url = "/info/ticker"
    payload = {
        'order_currency': order_currency,
        'payment_currency': "KRW",
    }
    update = self._query(url, payload)
    return update


def parse_trade_msg(msg):
  res = list()
  for entry in msg['data']:
    search_type = int(entry['search'])
    if search_type != 1 and search_type != 2:
      continue
    ts = int(entry['transfer_date'])
    dt_obj = datetime.fromtimestamp(ts / 1000000)
    price = float(entry['price'])
    qty = float(entry['units'])
    res.append({'ts': dt_obj, 'price': price, 'qty': qty})
  return res


def parse_summary_msg(msg):
  data = msg['data']
  avg_price = float(data['average_price'])
  qty_1day = float(data['volume_1day'])
  qty_7day = float(data['volume_7day'])
  print(f"Currency: {data['order_currency']}")
  print("(in KRW)")
  print(f"Average Price(Recent 1day): {avg_price:,}")
  print(f"Total Qty(Recent 1day): {qty_1day:,}")
  print(f"Total Qty(Recent 7day): {qty_7day:,}")
  print(f"Total Turnover(Recent 1day): {qty_1day * avg_price:,}")
  print(f"Total Turnover(Recent 7day)~ {qty_7day * avg_price:,}")
  return data


def print_fill_stat(fill_stats):
  print("Total Count  : ", len(fill_stats))
  if len(fill_stats) > 0:
    print("First Fill   : ", fill_stats[-1])
    print("Last Fill    : ", fill_stats[0])
  turnover = 0.0
  for trs in fill_stats:
    turnover += trs['price'] * trs['qty']
  print(f"Turnover(KRW): {turnover:,}")


def main(_):
  key_file = flags.FLAGS.key_file
  msc = MySpotClient(key_file=key_file)
  currency = flags.FLAGS.currency
  query_type = int(flags.FLAGS.query_type)
  if query_type == 0:
    msg = msc.query_ticker(order_currency=currency).msg
    parse_summary_msg(msg)
  elif query_type == 1:
    fetch = int(flags.FLAGS.fetch)
    init_offset = int(flags.FLAGS.init_offset)
    filter_date_range = flags.FLAGS.filter_date
    temp_split = filter_date_range.split("-")
    use_time_filter = False
    if len(temp_split) == 2:
      use_time_filter = True
      start_date = temp_split[0]
      end_date = temp_split[-1]

    count = 50
    total_fill = list()
    for offset in range(init_offset, init_offset + fetch, count):
      msg = msc.query_info_user_transactions(order_currency=currency,
                                            payment_currency="KRW",
                                            offset=offset,
                                            count=count).msg
      parsed_msg = parse_trade_msg(msg)
      total_fill += parsed_msg

    pick_range_data = list()
    for trs in total_fill:
      trs_date_str = trs['ts'].strftime("%Y%m%d")
      if use_time_filter:
        if trs_date_str < start_date or trs_date_str > end_date:
          continue
      pick_range_data.append(trs)
    print("-- Before Filter --")
    print_fill_stat(total_fill)
    print("\n-- After Filter --")
    print_fill_stat(pick_range_data)


if __name__ == '__main__':
  init_flags()
  app.run(main)

"""
Usage
* User should run on exact ip binding machine. *
./pyrunner python/experimental/taekwon/bithumb_fill.py --key_file ~/config/chpark2 --currency=ETH --query_type=0
./pyrunner python/experimental/taekwon/bithumb_fill.py --key_file ~/config/chpark0 --currency=BTC --query_type=1 \
--init_offset=2000 --fetch=10000 --filter_date=20220808-20220809
"""
